package com.yuandian.customer.perception.controller;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.yuandian.api.customer_perception.po.BusinessComplianceStatisticsParms;
import com.yuandian.api.customer_perception.po.StepDetailParams;
import com.yuandian.api.customer_perception.vo.ComOperatorOverviewVO;
import com.yuandian.api.customer_perception.vo.StepDetailVo;
import com.yuandian.bpm.common.core.util.R;
import com.yuandian.customer.perception.service.BusinessComplianceStatisticsService;
import com.yuandian.utils.BeanUtils;
import com.yuandian.utils.PageDataInfo;
import com.yuandian.utils.YDateUtil;
import com.yuandian.utils.poi.ExcelTitleUtils;
import com.yuandian.utils.poi.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 说明：业务合规性controller
 * @Author LinShiHe
 * @Date 2021-05-18
 */
@Slf4j
@RestController
@RequestMapping("/compliance/business")
public class BusinessComplianceController {

/*
    @Autowired
    private IStepDetailService stepDetailService;	TODO
*/

    @Autowired
    private BusinessComplianceStatisticsService businessComplianceStatisticsService;

/*
    @Autowired
    private ISearchOptionService searchOptionService;	TODO 远程调用
*/

    /**
     * 查询不合规操作员人数
     * @param params
     * @return int[]
     */
    @PostMapping("/queryUnComplianceOperatorNumber")
    public R<Object> queryUnComplianceOperatorNumber(@RequestBody BusinessComplianceStatisticsParms params){
        List<Long>  numbers = businessComplianceStatisticsService.queryUnComplianceOperatorNumber(params);
        return R.ok(numbers);
    }

     /**
     * 分页查询操作员总览列表
     * @param params
     * @return 通用返回对象
     */
    @PostMapping("/queryOperatorOverview")
    public R<Object> queryOperatorOverview(@RequestBody BusinessComplianceStatisticsParms params) {
        PageDataInfo info = businessComplianceStatisticsService.queryOperatorOverview(params);
        return R.ok(info);
    }

    /**
     * 操作员总览列表下载
     * @param params
     * @return 通用返回对象
     */
    @PostMapping("/downloadOperatorOverview")
    public void downloadOperatorOverview(@RequestBody BusinessComplianceStatisticsParms params, HttpServletResponse response) throws ParseException, IOException {
        List<ComOperatorOverviewVO> list = new ArrayList<>();
        try {
            list =  businessComplianceStatisticsService.downloadOperatorOverview(params);
        } catch (Exception e) {
            log.error("所选时间表不存在!但表格需要正常导出.");
        }
        int index = 1;
        for (ComOperatorOverviewVO vo : list) {
            vo.setId(index++);
            if (vo.getOperatorId() == null || vo.getOperatorId().equals("")) {
                vo.setOperatorId("-");
            }
            if (vo.getOperatorName() == null || vo.getOperatorName().equals("")) {
                if (Objects.equals(vo.getOperatorId(), "-")) {
                    vo.setOperatorName("-");
                } else {
                    vo.setOperatorName("未知");
                }
            }
        }
        String title = "操作员总览列表";
        String fileName = title + System.currentTimeMillis();

        //设置大标题
        List<String> titleParams = new ArrayList<>();
        titleParams.add(title);
        if (params.getSystemId() != null) {
//            titleParams.add(searchOptionService.querySystemName(params.getSystemId()));	TODO 远程调用
        }
        if (StringUtils.isNotEmpty(params.getBusinessCode())) {
//            titleParams.add(searchOptionService.queryBusinessName(params.getBusinessCode()));	TODO 远程调用
        }
        String formTitleName = ExcelTitleUtils.formTitleName(titleParams,params.getStartTime(),params.getEndTime());

        List<List<String>> headList = new ArrayList<>();
        List<String> titleList = Arrays.asList("序号","操作员ID", "姓名","业务不合规类型", "发生次数", "最早操作时间","最近操作时间");
        titleList.forEach(s -> {
            List<String> childHeadList = new ArrayList<>();
            childHeadList.add(formTitleName);
            childHeadList.add(s);
            headList.add(childHeadList);
        });

        ExcelUtil.writeExcel(ComOperatorOverviewVO.class, fileName, title, list, headList,20, response);
    }

    /**
     * 分页查询XX(工号)操作员(姓名)不合规业务总览列表
     * @param params
     * @return 通用返回对象
     */
    @PostMapping("/queryOneOperatorStatistic")
    public R<Object> queryOneOperatorStatistic(@RequestBody BusinessComplianceStatisticsParms params) {
        PageDataInfo info = businessComplianceStatisticsService.queryOneOperatorStatistic(params);
        return R.ok(info);
    }

    /**
     * 下载XX(工号)操作员(姓名)不合规业务总览列表
     * @param params
     * @return 通用返回对象
     */
    @PostMapping("/downloadOneOperatorStatistic")
    public void downloadOneOperatorStatistic(@RequestBody BusinessComplianceStatisticsParms params, HttpServletResponse response) {
        try {
            businessComplianceStatisticsService.downloadOneOperatorStatistic(params, response);
        } catch (Exception e) {
            e.printStackTrace();
	   }
    }

    /**
     * 分页查询XX(工号)操作员(姓名)不合规业务列表
     * @param params 业务不合规请求参数
     * @return 通用返回对象
     */
    @PostMapping("/queryViolationBusinessList")
    public R<PageDataInfo> queryViolationBusinessList(@RequestBody BusinessComplianceStatisticsParms params) {
        return businessComplianceStatisticsService.queryViolationBusinessList(params);
    }

    /**
     * XX(工号)操作员(姓名)不合规业务列表下载
     * @param params 业务不合规请求参数
     * @return 通用返回对象
     */
    @PostMapping("/queryViolationBusinessListExport")
    public void queryViolationBusinessListExport(@RequestBody BusinessComplianceStatisticsParms params, HttpServletResponse response) throws IOException, ParseException {
        try {
            businessComplianceStatisticsService.queryViolationBusinessListExport(params,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据搜索条件查询各种不合规类型的数据量
     * @param params 查询参数（工号、营业员姓名、业务编码、业务不合规类型、统计时间等）
     * @return 通用返回对象
     */
    @GetMapping("/queryEchartDataByUnComplianceType")
    public R<Object> queryEchartDataByUnComplianceType(BusinessComplianceStatisticsParms params) {
        R<Object> res = businessComplianceStatisticsService.queryEchartDataByUnComplianceType(params);
        return res;
    }

     /**
     * 查询不合规步骤明细列表
     * @param params 步骤不合规请求参数
     * @return 通用返回对象
     */
    @PostMapping("/list")
    public R<Object> list(@RequestBody StepDetailParams params) {
        try{
            if (StringUtils.isNotBlank(params.getServerResCode())){
                Integer.parseInt(params.getServerResCode());
            }
        }catch (Exception e){
            PageDataInfo pageDataInfo=new PageDataInfo(0,new ArrayList<>());
           return R.ok(pageDataInfo);
        }
		PageDataInfo info = businessComplianceStatisticsService.queryStepDetailList(params);

        return R.ok(info);
    }

    /**
     * 不合规步骤明细列表下载
     * @param params 步骤不合规请求参数
     * @return 通用返回对象
     */
    @PostMapping("/listExport")
    public void listExport(@RequestBody StepDetailParams params, HttpServletResponse response) throws IOException {
        PageDataInfo pageDataInfo = BeanUtils.cast(list(params).getData());
        List<StepDetailVo> list = new ArrayList<>();
        try {
            list = BeanUtils.cast(pageDataInfo.getData());
        } catch (Exception e) {
            log.error("所选时间表不存在!但表格需要正常导出.");
        }
        list.forEach(stepDetailVo -> {
            if (stepDetailVo.getRequestIp() != null && stepDetailVo.getRequestPort() != null){
                stepDetailVo.setRequestIpAndPort(stepDetailVo.getRequestIp()+":"+stepDetailVo.getRequestPort());
            }
            if (stepDetailVo.getResponseIp() != null && stepDetailVo.getResponsePort() != null){
                stepDetailVo.setResponseIpAndPort(stepDetailVo.getResponseIp()+":"+stepDetailVo.getResponsePort());
            }

            if (stepDetailVo.getDealTime()!=null) {
//                float dealTime=stepDetailVo.getDealTime()/1000.0f/1000.0f;
//                String dealTimeStr=String.format("%.2f", dealTime)+"秒";
//                stepDetailVo.setDealTimeStr(dealTimeStr);
                stepDetailVo.setDealTimeStr(YDateUtil.getMinSecond(stepDetailVo.getDealTime()/1000.0f));
            }


            if (stepDetailVo.getServerResponseTime()!=null) {
                stepDetailVo.setServerResponseTimeStr(YDateUtil.getMinSecond(stepDetailVo.getServerResponseTime()/1000.0f));
            }


            if (stepDetailVo.getDealState() != null) {
                stepDetailVo.setDealStateStr(stepDetailVo.getDealState()==1?"成功":"失败");
            }
        });
        for (int i = 0; i <list.size() ; i++) {
            StepDetailVo stepDetailVo=list.get(i);
            stepDetailVo.setNum(i+1);
        }
        String title = "不合规步骤详情";
        String fileName = title + System.currentTimeMillis();

        //设置大标题
        List<String> titleParams = new ArrayList<>();
        titleParams.add(title);
        titleParams.add(params.getBusinessName());
        titleParams.add(params.getOperatorId());
        titleParams.add(params.getOperatorName());
        String formTitleName = ExcelTitleUtils.formTitleName(titleParams,params.getStartTime(),params.getEndTime());
        List<List<String>> headList = new ArrayList<>();
        List<String> titleList = Arrays.asList("序号","请求URL", "业务名称", "步骤名称", "步骤类型", "请求IP端口", "响应IP端口", "响应状态", "系统返回码","自定义返回码",
                "告警数","请求开始时间","响应结束时间","处理时长","服务端耗时");
        titleList.forEach(s -> {
            List<String> childHeadList = new ArrayList<>();
            childHeadList.add(formTitleName);
            childHeadList.add(s);
            headList.add(childHeadList);
        });

        ExcelUtil.writeExcel(StepDetailVo.class, fileName, title, list, headList,20, response);
    }

}
